package org.coody.framework.minicat.handle;

import java.io.IOException;
import java.net.Socket;

import org.coody.framework.minicat.container.ServletContainer;
import org.coody.framework.minicat.entity.MinitCatHttpInstance;
import org.coody.framework.minicat.exception.BadRequestException;
import org.coody.framework.minicat.servlet.HttpServlet;
import org.coody.framework.minicat.threadpool.MiniCatThreadPool;

public class ServletHandle {

	public static void doHandle(final Socket socket) throws IOException {
		MiniCatThreadPool.HTTP_POOL.execute(new Runnable() {
			public void run() {
				MinitCatHttpInstance instance = null;
				try {
					instance = new MinitCatHttpInstance(socket);
					instance.buildRequest();
					HttpServlet servlet = ServletContainer.getServlet(instance.getRequest().getRequestURI());
					if (servlet == null) {
						instance.buildResponse(404, "page not found");
						return;
					}
					servlet.doService(instance.getRequest(), instance.getResponse());
					instance.buildResponse();
				} catch (BadRequestException e) {
					e.printStackTrace();
					try {
						instance.buildResponse(400, "400 bad request");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} catch (IOException e) {
					e.printStackTrace();
					try {
						instance.buildResponse(500, "error execution");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} finally {
					instance.flushAndClose();
				}
			}
		});

	}
}
